
------------------------------------------------------
--  Author : Team B
--  Description :main scene use when play game
------------------------------------------------------
display.setStatusBar(display.HiddenStatusBar)

module(...,package.seeall)
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()

local facebook = require "facebook"
local loqsprite = require('loq_sprite') -- load the sprite sheet module
local widget = require ( "widget" )

local nfactory = loqsprite.newFactory("fall","run","standup","sloping1","sloping2","sloping3",
													"rightSloping1","rightSloping2","rightSloping3")
local baseline = 3*display.viewableContentHeight/4


--create Chi Pheo
local ninja = nfactory:newSpriteGroup("RunSprite")
-- define 
local mapGame = {}
local score
local viewItem1,viewItem2,viewItem3,
		viewNumberItem1,viewNumberItem2,viewNumberItem3
local numberItem1,numberItem2,numberItem3 
local scoreText

local widthItem = display.viewableContentWidth/20
local heightItem = display.viewableContentWidth/20
local minDisObstacle = 160
local maxDisObstacle = 180
local numberItem = 10
local scoreTextWidth = 40
local scoreTextHeight = 20
local backBtn,shareFaBtn,replayBtn
local score,countScore
local forceNinja = 10
	--use on accelerometer event
local const = 5
	--direct of force
local direct="left"
	--limit of force
local leftslop1 = 40
local leftslop2 = 80
local leftslop3 = 120
local rightslop1 = -40
local rightslop2 = -80
local rightslop3 = -120
local forceapply = 0
local die = false
--force per frame

local fpfr = 1


-- facebook connect
--local shareFaBtn

local onFBTouch = function( event )
	if event.phase == "release" then
		--		Facebook AppID 131976793589185
		local fbAppID = "131976793589185"	--> (string) Your FB App ID from facebook developer's panel
		local appName = "Tilt Monster"
		local facebookListener = function( event )
			if ( "session" == event.type ) then
				-- upon successful login, update their status

				if ( "login" == event.phase ) then
					local function onComplete( event )
						if "clicked" == event.action then
							local i = event.index
							if 1 == i then
							-- Do nothing; dialog will simply dismiss
							elseif 2 == i then
							-- Open URL if "Learn More" (the 2nd button) was clicked

							end
						end
					end

					local theMessage = "Got a score of " .. score .. " on " .. appName .. "!"
					
					facebook.request( "me/feed", "POST", {
						message=theMessage,
						name=appName,
						caption="Download and compete with me!",
						link="http://itunes.apple.com/us/app/your-app-name/id382456881?mt=8",
						category="Game",
						picture="https://picasaweb.google.com/lh/photo/ysP8FVwz39VzOUj3D_oYrtMTjNZETYmyPJy0liipFm0?feat=directlink" }
					)
--					alert = native.showAlert("OK", "Post Complete", { "OK", "CANCEL" }, onComplete )
					-- The "link" parameter can be the Android Market app link or a website URL of your choosing
				end
			end
		end
		
		facebook.login( fbAppID, facebookListener, { "publish_stream" } )
	end
end
--print(widthItem)
-----------------------------------------------------------
-- Create Animation
-----------------------------------------------------------
 

function createMap()
	
	local score = 0
	local widthMap,heightMap =  math.random(40,display.viewableContentWidth - 40), 
													display.viewableContentHeight + 40;
	 for i=1,numberItem,1 do 
			local j = math.random(1,3)
			if j == 1 then
				mapGame[i] = display.newImage("iteam1.png")
				mapGame[i].tag = 1
			elseif  j == 2 then
				mapGame[i] = display.newImage("item2.png")
				mapGame[i].tag = 2
			else 
				mapGame[i] = display.newImage("item3.png")
				mapGame[i].tag = 3
			end
			local yDis = math.random(minDisObstacle, maxDisObstacle )
			--yDis = 0
			mapGame[i].width = 30
		    mapGame[i].height = 30
			mapGame[i]:setReferencePoint( display.BottomLeftReferencePoint )
		    mapGame[i].x = math.random( 40, display.viewableContentWidth - 40)
		    mapGame[i].y = heightMap + yDis
		    heightMap =  heightMap + yDis
	end
	
end

       
--run animation
local function runAnimation()
	--ninja.rotation=180	
	ninja:prepare("RunSprite")
	ninja:play("RunSprite")
	
end


--slop to left
local function slop2left1Animation()
	ninja:prepare("sloping1")
	ninja:play("sloping1")  	
end	

local function slop2left2Animation()
	ninja:prepare("sloping2")
	ninja:play("sloping2")  	
end	

local function slop2left3Animation()
	ninja:prepare("sloping3")
	ninja:play("sloping3")  	
end	

-- fall to left on way
local function fall2leftAnimation()
	ninja:prepare("FallSprite")
	ninja:play("FallSprite")  	
end	

--stand up 
local function standupAnimation()
	ninja:prepare("StandUp")
 	ninja:play("StandUp")  	
end 	

--slop to right
local function slop2right1Animation()
	ninja:prepare("rightSloping")
	--ninja.x=display.viewableContentWidth/2-ninja.width/2+80
	ninja:play("rightSloping")  	
end	

local function slop2right2Animation()
	ninja:prepare("rightSloping2")
	--ninja.x=display.viewableContentWidth/2-ninja.width/2+80
	ninja:play("rightSloping2")  	
end	

local function slop2right3Animation()
	ninja:prepare("rightSloping3")
	--ninja.x=display.viewableContentWidth/2-ninja.width/2+80
	ninja:play("rightSloping3")  	
end	

--fall to right on way
local function fall2rightAnimation()
		if ninja.xScale >0 then
			ninja.xScale=ninja.xScale*-1	
			ninja.x=display.viewableContentWidth/2-ninja.width/2+80
			ninja:prepare("FallSprite")
			ninja:play("FallSprite")  	
		end	
end	

-----------------------------------------------------------
-- Create Text and Display Objects
-----------------------------------------------------------

local function checkCollisionWithObstack(x1,x2,y1,y2,x3,x4,y3,y4) 
	--print(x1..x2..y1..y2..x3..x4..y3..y4)
    if x1 <= x3 and x3 <= x2 and y1 <=y3 and y3<=y2 then
        return x3,y3
    elseif x1 <= x3 and x3 <= x2 and y1 <=y4 and y4<=y2 then
         return x3,y3
     elseif x1 <= x4 and x4 <= x2 and y1 <=y4 and y4<=y2 then
        return x3,y3
    elseif x1 <= x4 and x4 <= x2 and y1 <=y3 and y3<=y2 then
        return x3,y3
    elseif x3 <= x1 and x1 <= x4 and y3 <=y1 and y1<=y4 then 
        return x3,y3
    elseif x3 <= x1 and x1 <= x4 and y3 <=y2 and y2<=y4 then 
        return x3,y3
    elseif x3 <= x2 and x2 <= x4 and y3 <=y1 and y1<=y4 then
        return x3,y3
    elseif x3 <= x2 and x2 <= x4 and y3 <=y2 and y2<=y4 then
        return x3,y3    
    else 
        return -1,-1
    end
end

 
-- Text parameters
local labelx = 50
local x = 220
local y = 55
local fontSize = 24

local frameUpdate = false					-- used to update our Text Color (once per frame)

local function onFrame()
	    --print("hehe")
		countScore = countScore + 1
		if countScore == 30 then 
			score = score +1 
			countScore = 0
			--scoreText.text = "Score:"..score
		end
		frameUpdate = true
		if die then print("hehe") 
		else
			if direct == "left" then 
				forceNinja = forceNinja + fpfr	
				forceapply = forceapply + fpfr	
			else 
				forceNinja = forceNinja - fpfr
			    forceapply = forceapply - fpfr
			end
		end
		ninja.x = ninja.x - forceapply
		
		for i = 1, numberItem, 1 do
			if mapGame[i] .y < display.viewableContentHeight/3 then
					mapGame[i].isVisible = false
					local j = math.random(1,3)
					if j == 1 then
						mapGame[i] = display.newImage("iteam1.png")
						mapGame[i].tag = 1
					elseif j == 2 then
						mapGame[i] = display.newImage("item2.png")
						mapGame[i].tag = 2
					else 
						mapGame[i] = display.newImage("item3.png")
						mapGame[i].tag = 3
					end
					mapGame[i].width = 30
	    			mapGame[i].height = 30
	    			mapGame[i]:setReferencePoint( display.BottomLeftReferencePoint )
					local yDis = math.random(minDisObstacle, maxDisObstacle )
					if i == 1 then 
	                    mapGame[i].y  = mapGame[numberItem].y + yDis
	                else 
	                    mapGame[i].y  = mapGame[i-1].y + yDis
	                end
	                mapGame[i].x = math.random(40,display.viewableContentWidth - 40)
	                mapGame[i].isVisible = true         
			else
				mapGame[i].y = mapGame[i].y - 0.5
				if mapGame[i].x < display.viewableContentWidth/2 then 
					 local view = ( display.viewableContentWidth/2 - mapGame[i].x )/(display.viewableContentHeight*2)
					 mapGame[i].x = mapGame[i].x + view
				elseif mapGame[i].x > display.viewableContentWidth/2 then
				   mapGame[i].x = mapGame[i].x - (mapGame[i].x - display.viewableContentWidth/2)/(display.viewableContentHeight*2)				 
				end
				if mapGame[i].isVisible then
					local x,y = checkCollisionWithObstack(ninja.x,ninja.x+20,ninja.y-ninja.height/4 ,ninja.y,
											mapGame[i].x , mapGame[i].x + widthItem,mapGame[i].y -heightItem , mapGame[i].y);
				   if x ~= -1 and y ~= -1 then
				   	if mapGame[i].tag == 1 then
	                   	numberItem1 = numberItem1 + 1
	                       mapGame[i].isVisible = false
	                   	viewNumberItem1.text = numberItem1
	                   elseif mapGame[i].tag == 2 then
	                   	numberItem2 = numberItem2 + 1
	                   	mapGame[i].isVisible = false
	                   	viewNumberItem2.text = numberItem2
	                    elseif mapGame[i].tag == 3 then
	                    	numberItem3 = numberItem3 + 1
	                    	mapGame[i].isVisible = false
	                    	viewNumberItem3.text = numberItem3
	                    end       
				   end
				end
		end		
		end
end

local function onAccelerate( event )
		forceapply = const*event.yGravity
		if event.yGravity > 0 then 
			direct = "left"
		else 	
			direct = "right"
		end	
		forceNinja = forceNinja+forceapply
		scoreText.text = forceNinja
		if forceNinja >0 and forceNinja <=leftslop1 then 
			if ninja:sequence() ~= "sloping1" then
				
				slop2left1Animation()
			end	
		elseif forceNinja <0 and forceNinja >=rightslop1 then 
			if ninja:sequence()~="rightSloping" then
				slop2right1Animation()
			end	
		elseif forceNinja ==0 then 
			if ninja:sequence()~="RunSprite" then
				runAnimation()
			end	
		elseif forceNinja>leftslop1 and forceNinja<=leftslop2 then 
			if ninja:sequence()~="sloping2" then
				slop2left2Animation()
			end	
		elseif forceNinja<rightslop1 and forceNinja>=rightslop2 then 
			if ninja:sequence()~="rightSloping2" then
				slop2right2Animation()
			end	
		elseif forceNinja>leftslop2 and forceNinja<=leftslop3 then 
			if ninja:sequence()~="sloping3" then	
				slop2left3Animation()
			end	
		elseif forceNinja <rightslop2 and forceNinja >=rightslop3 then 
			if ninja:sequence()~="rightSloping3" then
				viewNumberItem1.text = "Phai:"..forceNinja.."|"..rightslop2.."|"..rightslop3
				slop2right3Animation()
			end	
		elseif forceNinja>leftslop3 then 
			if ninja:sequence()~="FallSprite" then
				finishGame()
				fall2leftAnimation()
			end
			die=true
		elseif forceNinja<rightslop3 then 
			if ninja:sequence()~="FallSprite" then
				finishGame()
				fall2rightAnimation()
			end;
			die=true 			
		end							
		 frameUpdate = false		-- update done 	
	end
	
local function main()
	ninja.xScale = 0.25
	ninja.yScale = 0.25
	score,countScore = 0,0
	numberItem1 = 0
	numberItem2 = 0
	numberItem3 = 0
	viewNumberItem1.text = numberItem1
    viewNumberItem3.text = numberItem2
    viewNumberItem2.text = numberItem3
	---
	system.setAccelerometerInterval(45)
	forceNinja = 10
	--use on accelerometer event
	const = 5
	--direct of force
	direct="left"
	--limit of force
	leftslop1 = 40
	leftslop2 = 80
	leftslop3 = 120
	rightslop1 = -40
	rightslop2 = -80
	rightslop3 = -120
	forceapply = 0
	die = false
	--force per frame
	fpfr = 1
	
	backBtn.isVisible = false
	shareFaBtn.isVisible = false
	replayBtn.isVisible = false
	
	--init force
	runAnimation()
	ninja:setReferencePoint( display.BottomLeftReferencePoint )
	ninja.x = display.viewableContentWidth/2
	ninja.y = 2*display.viewableContentHeight/3
	
	---
	createMap()
	Runtime:addEventListener ( "enterFrame", onFrame )
	Runtime:addEventListener ("accelerometer", onAccelerate)
	
end


---------------


local function backBtnPress()
 	
 	return true
 end
 
 local function shareFaBtnPress()
 	-- Share facebook
	 return true
 end

local function  replayBtnPress()
		print("hehe")
		Runtime:removeEventListener ( "enterFrame", onFrame )
		Runtime:removeEventListener ("accelerometer", onAccelerate)
		for i=1,numberItem,1 do 
			mapGame[i]:removeSelf()
		end
		main()
	return true
end

function finishGame()
	backBtn.isVisible = true
	replayBtn.isVisible = true
	shareFaBtn.isVisible = true
	Runtime:removeEventListener ( "enterFrame", onFrame )
	Runtime:removeEventListener ("accelerometer", onAccelerate)
	return true
end

-- Called when the scene's view does not exist:
function scene:createScene( event )
        local group = self.view 
        
		local background = display.newImage( "background_ALL.png" )
        background.width = display.viewableContentWidth
        background.height = display.viewableContentHeight
	    background:setReferencePoint( display.BottomLeftReferencePoint  )
	    --background.x, background.y = 0, display.viewableContentHeight
	    background.x = 0
	    background.y =  320
		
	   local backgroundLeft = display.newImage("background_LEFT.png")
	   backgroundLeft.width = display.viewableContentWidth
       backgroundLeft.height = display.viewableContentHeight
	   backgroundLeft:setReferencePoint( display.BottomLeftReferencePoint  )
	   --background.x, background.y = 0, display.viewableContentHeight
	   backgroundLeft.x = 0
	   backgroundLeft.y =  display.viewableContentHeight
	   
	   local backgroundRight = display.newImage("background_RIGHT.png")
	   backgroundRight.width = display.viewableContentWidth
       backgroundRight.height = display.viewableContentHeight
	   backgroundRight:setReferencePoint( display.BottomLeftReferencePoint  )
	   --background.x, background.y = 0, display.viewableContentHeight
	   backgroundRight.x = 0
	   backgroundRight.y =  display.viewableContentHeight
	   	   
	   print("Device:"..display.viewableContentWidth.."|"..display.viewableContentHeight)
        local playBtn = widget.newButton{
			--label="restart",
			labelColor = { default={255}, over={128} },
			default="lr_menu_start.png",
			width=154, height=30,
	        onPress = main,
		}
		playBtn:setReferencePoint( display.TopLeftReferencePoint )
		playBtn.x = display.viewableContentWidth*0.5-playBtn.width/2
		playBtn.y = 20
		
		replayBtn= widget.newButton{
			label="replay",
			labelColor = { default={0}, over={128} },
			width = 100, height=30,
	        onPress = replayBtnPress
		}
		replayBtn:setReferencePoint( display.TopLeftReferencePoint )
		replayBtn.x = display.viewableContentWidth/3
		replayBtn.y = display.viewableContentHeight/3
		
		shareFaBtn= widget.newButton{
			label="shareFace",
			labelColor = { default={0}, over={128} },
			width=100, height = 30,
--	        onPress = shareFaBtnPress
			onEvent = onFBTouch
		}
		shareFaBtn:setReferencePoint( display.TopLeftReferencePoint )
		shareFaBtn.x = display.viewableContentWidth*2/3
		shareFaBtn.y = display.viewableContentHeight/3
		
		backBtn= widget.newButton{
			label="back",
			labelColor = { default={0}, over={128} },
			width=100, height=30,
	        onPress = backBtnPress
		}
		backBtn:setReferencePoint( display.TopLeftReferencePoint )
		backBtn.x = display.viewableContentWidth/2
		backBtn.y = display.viewableContentHeight/2
		
		viewItem1 = display.newImageRect("iteam1.png", widthItem , heightItem)
		viewItem1:setReferencePoint( display.TopLeftReferencePoint )
		viewItem1.x = display.viewableContentWidth/20
        viewItem1.y = display.viewableContentHeight/20
        
        viewNumberItem1 = display.newText("", viewItem1.x + widthItem + 10, viewItem1.y, native.systemFont, 16)
		viewNumberItem1:setReferencePoint( display.TopLeftReferencePoint )
		viewNumberItem1:setTextColor(255, 255, 255)
		viewNumberItem1.size = 16
		viewNumberItem1.x =  viewItem1.x + widthItem + 10
		viewNumberItem1.y = viewItem1.y 
        
        viewItem2 = display.newImageRect("item2.png", widthItem , heightItem)
		viewItem2:setReferencePoint( display.TopLeftReferencePoint )
		viewItem2.x = display.viewableContentWidth/20
        viewItem2.y = viewItem1.y  + display.viewableContentHeight/10
        
        viewNumberItem2 = display.newText("", viewItem2.x + widthItem + 10, viewItem2.y, native.systemFont, 16)
		viewNumberItem2:setReferencePoint( display.TopLeftReferencePoint )
		viewNumberItem2:setTextColor(255, 255, 255)
		viewNumberItem2.size = 16
		viewNumberItem2.x =  viewItem2.x + widthItem + 10
		viewNumberItem2.y = viewItem2.y 
		
        viewItem3 = display.newImageRect("item3.png", widthItem , heightItem)
		viewItem3:setReferencePoint( display.TopLeftReferencePoint )
		viewItem3.x = display.viewableContentWidth/20
        viewItem3.y = viewItem2.y  + display.viewableContentHeight/10			
		
		viewNumberItem3 = display.newText("", viewItem3.x + widthItem + 10, viewItem3.y, native.systemFont, 16)
		viewNumberItem3:setReferencePoint( display.TopLeftReferencePoint )
		viewNumberItem3:setTextColor(255, 255, 255)
 	   
		viewNumberItem3.size = 16
		viewNumberItem3.x =  viewItem3.x + widthItem + 10
		viewNumberItem3.y = viewItem3.y
		
		scoreText = display.newText("", scoreTextWidth,  scoreTextHeight , native.systemFont, 16)
		scoreText:setReferencePoint( display.TopLeftReferencePoint )
		scoreText:setTextColor(255, 255, 255)
 	   scoreText.text = "Score:0"
		scoreText.size = 16
		scoreText.x =  display.contentWidth - 2*scoreTextWidth
		scoreText.y = scoreTextHeight
		 
		main()
		playBtn.isVisible = false
		
		group:insert(background)
		group:insert(backgroundLeft)
		group:insert(backgroundRight)
		group:insert(viewItem1)
		group:insert(playBtn)
		for i=1,numberItem,1 do 
			group:insert(mapGame[i])
		end
		group:insert(ninja)
		--group:insert(mapGame[i])
		--group:insert(backleft)
end

----- 



-- Called BEFORE scene has moved onscreen:
function scene:willEnterScene( event )
        local group = self.view
        
        -----------------------------------------------------------------------------

end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
        local group = self.view 
        
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)

        -----------------------------------------------------------------------------

end


-- Called AFTER scene has finished moving offscreen:
function scene:didExitScene( event )
        local group = self.view

        ----------------------------------------------------------------------------
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
        local group = self.view

        ----------------------------------------------------------------------------

        ---------------------------------------------------------------------------

end


-- Called if/when overlay scene is displayed via storyboard.showOverlay()
function scene:overlayBegan( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.

        -----------------------------------------------------------------------------

end


-- Called if/when overlay scene is hidden/removed via storyboard.hideOverlay()
function scene:overlayEnded( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.
        
        -----------------------------------------------------------------------------

end



---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "willEnterScene" event is dispatched before scene transition begins
scene:addEventListener( "willEnterScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "didExitScene" event is dispatched after scene has finished transitioning out
scene:addEventListener( "didExitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

-- "overlayBegan" event is dispatched when an overlay scene is shown
scene:addEventListener( "overlayBegan", scene )

-- "overlayEnded" event is dispatched when an overlay scene is hidden/removed
scene:addEventListener( "overlayEnded", scene )

---------------------------------------------------------------------------------

return scene

	
